// pages/my/cash/affirmRecharge.js
const App = getApp();
const util = require('../../../utils/util.js');
const api = require('../../../utils/api.js');


//支付方式
var payType = ''

Page({
  data: {
    items: [
      {
        name: 'wxpay', value: '微信支付',
        memo: '推荐安装微信5.0及以上版本的用户使用',
        img: '../../../image/my/u2174.png',
        isSelect: true,   //   暂时只有微信支付，默认选中
      }
    ],
    form: {
      name: '',
      is_def: 0,
    },
    //页面数据
    buyerMsg:'',
    deliveryMsg:'',
    wetPayData:'',
    //OpenIdData:'',
    order_data:'',
    //页面跳转
    tapType_set: '',
    secondIndex: 0,
    contact_person: '',
    delivery_address:'',
    delivery_area_desc:'',
    num:'',
    //禁止按钮
    disabled: false,
  },
  //初始化数据加载
  onLoad: function (option) {

    this.setData({
      order_data: App.globalData.order_data,
      contact_person: App.globalData.order_data.contact_person,
      delivery_area_desc: App.globalData.order_data.delivery_area_desc,
      delivery_address: App.globalData.order_data.delivery_address,
      total_fee_sum: (App.globalData.order_data.total_fee * App.globalData.order_data.qty).toFixed(2),
      item_sale_price_sum: (App.globalData.order_data.item_sale_price * App.globalData.order_data.qty).toFixed(2),
      num: option.num
    })
    //this.getOpenId()
  },

/**
 * 生命周期函数--监听页面显示--回退部分刷新
 */
  onShow: function () {
    this.getDeliveryMsg()
    //重新启动按钮点击
    this.setData({
      disabled: false
    })
  },

 
  //跳转修改地址信息
  toDeliveryMsg(e){
    wx.navigateTo({
      url: '/pages/my/address/list/list'
    })
  },

  //加载收获地址信息
  getDeliveryMsg() {
    const self = this;
    let data = {
      service: 'member.consumerAddressFind',
      params: '{"is_major_addr":"Y","consumer_id":"11432431"}',
      url_type: 'member',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code 
    }
    var jsons = JSON.parse(data.params);
    jsons["consumer_id"] = App.globalData.memberInfo.member_id;
    data.params = JSON.stringify(jsons);

    //标签状态切换查询
    //let sign = util.getSign(data);
    //data.sign = sign;
    api.reqData({
      data,
      success: (res) => {
        //这个得写法和格式 setData({........})
        console.log("收获地址=======" + res.data);
        self.setData({
          deliveryMsg: res.data.data[0],
          contact_person: res.data.data[0].consignee,
          delivery_area_desc: res.data.data[0].area_desc,
          delivery_address: res.data.data[0].address
        })
      },
    })
  },

   /* 表单提交 */
  submitForm(e) {

    //判断收货地址为空的情况
    if (this.data.deliveryMsg == '') {
      wx.showToast({
        title: '收获信息不能为空',
        icon: 'fail',
        duration: 2000
      })
      return
    }
    //禁止重复点击按钮
    this.setData({
      disabled: true
    })

    //获取js_code
    const self = this;
    //let appid = App.globalData.appid;
    //let secret = App.globalData.appkey;
    //发起网络请求
    wx.login({
      success: function (res) {
        if (res.code) {


              self.setData({
                js_code: res.code
              })

              self.wetPay();

        }
      }
    })  
  },


  /* 获取prePayId */
  wetPay() {
    const self = this;
    console.log("payTpe>>>>>>>>" + payType)
   
    //精品自营商品支付(带存存储客户留言)
    let data = {
      service: 'finance.miniAppWechatPay',

      params: '{"data_source":"SJLY_17","payment_way_key":"ZFFS_02","detail":"", "amount":"", "seller_id":"10000001","buyer_id":"","js_code":"oA9D20EZogOYpVNKYEjfAVUWfGaQ","order_type_key":"","out_trade_body":"","order_type":"meitianhui","version_number":""}',

      url_type: 'finance',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code
    }

    var json = JSON.parse(data.params);
    //组装第一层数据
    let order_data = self.data.order_data;
    let order_type_str = order_data.order_type;
    //新加会过商品，下单需要区分出订单类型
    if (order_type_str == 2){
      json.order_type = 'huiguo';
      json.detail = '会过';
      json.order_type_key = 'DDLX_07'                    //  3月13号修改
    } else if (order_type_str==1){
      json.order_type = 'meitianhui'
      json.detail = '自营';
      json.order_type_key = 'DDLX_07'
    }
    console.log("payTpe>>>>>>>>" + payType)
    console.log(json)
    // 微信小程序 支付方式 ZFFS_26  
    //json.amount = order_data.item_sale_price;
    json.amount = (order_data.item_sale_price * order_data.qty).toFixed(2);;
    json.buyer_id = App.globalData.memberInfo.member_id;
    json.js_code = self.data.js_code;
    json.version_number = App.globalData.version;       //创建会过自营时传版本号


    //组装第二层数据
    let out_trade_body = {};
    out_trade_body["data_source"] = 'SJLY_17';      // 微信小程序 数据来源 SJLY_17
    out_trade_body["payment_way_key"] = 'ZFFS_02';  // 微信小程序 支付方式 ZFFS_02  
    out_trade_body["delivery_address"] = self.data.delivery_address + "" + self.data.delivery_area_desc;
    out_trade_body["contact_person"] = self.data.contact_person;
    out_trade_body["contact_tel"] = order_data.contact_tel;
    out_trade_body["remark"] = self.data.buyerMsg;
    out_trade_body["order_id"] = order_data.order_id;
    //out_trade_body["transaction_member_type"] = 'consumer';
    json.out_trade_body = out_trade_body;
    data.params = JSON.stringify(json);

    //let sign = util.getSign(data);
    //data.sign = sign;
    api.reqData({
      data,
      success: (res) => {
        //这个得写法和格式 setData({........})
        console.log(res.data + "---------------------------");
        console.log(JSON.stringify(res.data) + "---------------------------");
        if (res.data.rsp_code === 'succ') {
          self.setData({
            wetPayData: res.data.data
          })
          //调用微信支付
          self.pay()
        } else {
          wx.showToast({
            title: res.data.error_msg,
            icon: 'fail',
            duration: 2000
          })
        }
      },
    })
  },

  /* 微信支付 */
  pay: function () {   
    const self = this; 
    wx.requestPayment({
      timeStamp: self.data.wetPayData.timeStamp,
      nonceStr: self.data.wetPayData.nonceStr,
      package: self.data.wetPayData.package,
      signType: 'MD5',
      paySign: self.data.wetPayData.paySign,
      success: function (res) {
        // success  
        console.log(res)
        App.globalData.secondIndex = 2,
          App.globalData.status = 'confirmed',
          wx.switchTab({
          url: '/pages/buy/orderlist/orderlist',
            success: function (e) {
              var page = getCurrentPages().pop();
              if (page == undefined || page == null) return;
              page.initData();
              page.onLoad();
            }
          })
      },
      fail: function (res) {
        // fail  
        //跳转到订单待付款页面
          App.globalData.secondIndex = 1,
          App.globalData.status = 'processing',
          wx.switchTab({
            url: '/pages/buy/orderlist/orderlist',
            // success: function (e) {
            //   var page = getCurrentPages().pop();
            //   if (page == undefined || page == null) return;
            //   page.initData();
            //   page.onLoad();
            // }
          })
      },
      complete: function () {
        // complete  
        console.log("pay complete")
      }
    })
  },

  bindTextAreaBlur: function (e) {
    this.setData({
      buyerMsg: e.detail.value
    })
  },

  showToast(message) {
    App.WxService.showToast({
      title: message,
      icon: 'success',
      duration: 1500,
    })
      .then(() => App.WxService.navigateBack())
  },

  // selectPayType: function (e) {
  //   var selectPayId = e.target.dataset.payid;
  //   console.log("pay>>>>>>>>>>>" + selectPayId);
  //   //var that = this
  //   payType = selectPayId;

  //   for (var i = 0; i < this.data.items.length; i++) {
  //     if (this.data.items[i].name == selectPayId) {
  //       this.data.items[i].isSelect = true
  //     } else {
  //       this.data.items[i].isSelect = false
  //     }
  //   }   
  //   this.setData({
  //     items: this.data.items,
  //   })
  // }
  
})